<template>
    <div class="pager-container" v-if="getPageNumers > 1">
        <a @click="handleClick(1)" :class="props.current === 1 ? 'disable' : ''">|&lt;&lt;</a>
        <a :class="props.current === 1 ? 'disable' : ''" @click="handleClick(this.props.current - 1)">&lt;&lt;</a>
        <a v-for="n in createNumbers" :key="n" :class="n === props.current ? 'selected' : ''" @click="handleClick(n)">
            {{ n }}
        </a>
        <a :class="getPageNumers === props.current ? 'disable' : ''" @click="handleClick(props.current + 1)">&gt;&gt;</a>
        <a :class="getPageNumers === props.current ? 'disable' : ''" @click="handleClick(getPageNumers)">&gt;&gt;|</a>
    </div>
</template>

<script setup>
import { defineProps, computed } from "vue"
const props = defineProps({
    current: {
        //当前页数
        type: Number,
        default: 1,
    },
    total: {
        //数据总量
        type: Number,
        default: 0,
    },
    limit: {
        //一页显示多少
        type: Number,
        default: 10,
    },
    visibleNumber: {
        //可以看见的页码数量
        type: Number,
        default: 10,
    },
    handleChangePage: {
        type: Function,
    }
})
// 算出有多少页
const getPageNumers = computed(() => Math.ceil(props.total / +props.limit));

//可见最大页 
const visibleMax = computed(() => {
    let max = visibleMin.value + parseInt(props.limit) - 1;
    if (max > getPageNumers.value) {
        max = getPageNumers.value;
    }
    return max;
})

// 可见最小页
// 若在computed中使用了props也不可以直接进行拆解，否则也无法进行跟踪，无法进行即使响应
const visibleMin = computed(() => {
    let min = Math.round(props.current - props.visibleNumber / 2);
    if (min <= 0) {
        min = 1;
    }
    return min;
});

// 创建页码
const createNumbers = computed(() => {
    let num = [];
    for (let i = visibleMin.value; i <= visibleMax.value; i++) {
        num.push(i);
    }
    return num;
});

// 页码跳转
const handleClick = (newPage) => {

    if (newPage === props.current) {
        return;
    }
    if (newPage < 0) {
        newPage = 1;
    }
    if (newPage > getPageNumers.value) {
        newPage = getPageNumers.value;
    }
    props.handleChangePage(newPage);
}
</script>

<style lang="less" scoped>
.pager-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 20px 0;
}

.pager-container a {
    margin: 0 6px;
    color: #6b9eee;
    cursor: pointer;
}

.pager-container a.disable {
    color: #b4b8bc;
    cursor: not-allowed;
}

.pager-container a.selected {
    color: #373737;
    font-weight: bold;
    cursor: text;
}
</style>